<?php
namespace App\Models;

use App\Services\CommonService;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class GoodsCustom extends Model
{
    use HasFactory;

    protected $table = 'sp_goods_custom_2';
    protected $primaryKey = 'id';
    public $timestamps = false;

    protected function getGoodsAttribute($goods_id){
        $attribute = $this->where([['goods_id',$goods_id],['is_delete',CommonService::GOODS_IS_DELETE_NOT]])->select('field_title','field_val')->get();
        $attribute = $attribute ? $attribute->toArray() : array();
        return $attribute;
    }

    //添加
    protected function AddGoodsCustom($custom,$goods_id){
        foreach ($custom as $k=>$v){
            if(!empty($v['field_title']) && !empty($v['field_val'])){
                $custom_data = [];
                $custom_data['goods_id'] = $goods_id;
                $custom_data['field_title'] = $v['field_title'];
                $custom_data['field_val'] = $v['field_val'];
                $custom_data['type'] = 1;
                $custom_data['is_delete'] = CommonService::GOODS_IS_DELETE_NOT;
                $this->insert($custom_data);
            }
        }
    }

    //编辑
    protected function EditGoodsCustom($custom,$goods_id){
        $this->where([['goods_id',$goods_id],['is_delete',CommonService::GOODS_IS_DELETE_NOT]])->update(['is_delete'=>CommonService::GOODS_IS_DELETE_YES]);
        foreach ($custom as $k=>$v){
            if(!empty($v['field_title']) && !empty($v['field_val'])){
                $custom = $this->where([['goods_id',$goods_id],['field_title',$v['field_title']]])->select('id')->first();
                $custom = $custom ? $custom->toArray() : array();
                if(!empty($custom)){
                    $custom_data = [];
                    $custom_data['field_title'] = $v['field_title'];
                    $custom_data['field_val'] = $v['field_val'];
                    $custom_data['is_delete'] = CommonService::GOODS_IS_DELETE_NOT;
                    $this->where('id',$custom['id'])->update($custom_data);
                }else{
                    $custom_data = [];
                    $custom_data['goods_id'] = $goods_id;
                    $custom_data['field_title'] = $v['field_title'];
                    $custom_data['field_val'] = $v['field_val'];
                    $custom_data['type'] = 1;
                    $custom_data['is_delete'] = CommonService::GOODS_IS_DELETE_NOT;
                    $this->insert($custom_data);
                }

            }
        }
    }
}
